package com.example.springboot.controller;

import com.example.springboot.common.request.AddBookRequest;
import com.example.springboot.common.result.Result;
import com.example.springboot.common.request.BookListRequest;
import com.example.springboot.entity.Book;
import com.example.springboot.entity.Category;
import com.example.springboot.service.BookService;
import com.example.springboot.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public Result list() {
        return Result.success(bookService.list());
    }

    /**
     * 根据书名模糊查询
     * @param bookListRequest
     * @return
     */
    @GetMapping("/page")
    public Result page(BookListRequest bookListRequest) {
        return Result.success(bookService.page(bookListRequest));
    }

    /**
     * 添加图书
     * @param addBookRequest
     * @return
     * @throws Exception
     */
    @PostMapping("/save")
    public Result save(@RequestBody AddBookRequest addBookRequest) throws Exception {
        bookService.save(addBookRequest);
        return Result.success();
    }

    /**
     * 根据id获取需要修改的图书信息
     * @param id
     * @return
     */
    @GetMapping("/update/{id}")
    public Result getById(@PathVariable Integer id) {
        Book book = bookService.getById(id);
        return Result.success(book);
    }

    /**
     * 更新图书信息
     * @param addBookRequest
     * @return
     * @throws Exception
     */
    @PutMapping("/update")
    public Result editUser(@RequestBody AddBookRequest addBookRequest) throws Exception {
        bookService.update(addBookRequest);
        return Result.success();
    }

    /**
     * 根据id删除图书分类
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteById(@PathVariable Integer id) {
        bookService.deleteById(id);
        return Result.success();
    }

    /**
     * 查询所有级别分类
     * @return
     */
    @GetMapping("/getCategories")
    public Result getCategories() {
        List<Category> list = categoryService.list();
        List<Category> treeList = bookService.createTree(null, list); // null表示从第一级开始递归

        return Result.success(treeList);
    }


}
